<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\api\model\Order as customsOrder;
use catchAdmin\api\model\OrderSon as customsOrderSon;
use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\customs\model\OrderSon;
use catchAdmin\customs\model\XsOrder;
use catchAdmin\externalGoods\model\Areas;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\customs\model\Order;
use catchAdmin\externalGoods\model\CreditDeduction as CreditDeductionModel;
use catchAdmin\permissions\model\Users;
use catcher\CatchAuth;
use catcher\CatchResponse;
use think\Exception;
use think\facade\Db;
use think\helper\Str;


class TenantOrderService{

    //根据订单主键扣款操作
    public function creditDeductByOrderPk($order_pk){
        //防止重复扣费
        $creditWhere = [
            'order_pk'=>$order_pk,
            'is_refunded'=>0
        ];
        $creditModel = new CreditDeductionModel;
        $creditResult = $creditModel->where($creditWhere)->find();
        if($creditResult){
            return ['status'=>1, 'msg'=>'已经扣款过','data'=>$creditResult];
        }

        $orderInfo = (new customsOrder())->where('id',$order_pk)->find()->toArray();
        $tenant_id = $orderInfo['tenant_id'];
        $orderId = $orderInfo['orderId'];


        //1.授信额度
        $userInfo = (new Users())->where('id',$tenant_id)->lock(true)->find();
        $order_total_money = $this->getOrderTotalByOrderId($orderId);

//        if($order_total_money <= 0) return ['status'=>0, 'msg'=>'订单错误1'];
        if($order_total_money <= 0) {
            $order_total_money = $orderInfo['amount'];
        }

        if($order_total_money > $userInfo['credit_available_amount'] ) return ['status'=>0, 'msg'=>'授信额度不足'];

        $userInfo->credit_available_amount -= $order_total_money;
        $userResult =  $userInfo->save();

        $creditAddData = [
            'order_pk'=>$order_pk,
            'order_no'=>$orderId,
            'amount'=>$order_total_money,
            'account_residue'=>$userInfo['credit_available_amount'],
            'tenant_id'=>$tenant_id
        ];
        $creditAddResult = (new CreditDeductionModel())->save($creditAddData);


        if(!$userResult || !$creditAddResult){
            return ['status'=>0, 'msg'=>'扣款错误'];
        }
        return ['status'=>1, 'msg'=>'success'];
    }

    //根据订单ID得到结算价格
    public function getOrderTotalByOrderId($order_id){

        $tenant_id = (new customsOrder())->where('orderId',$order_id)->value('tenant_id');
        $orderList = (new customsOrderSon())->field('num,productId as goods_spu,sku_id')->where('orderId',$order_id)->select()->toArray();
        $total = 0;

        $tenantGoodsService = new TenantGoodsService;

        foreach ($orderList as $value){
            $goods_price =   $tenantGoodsService
                ->getTenantGoodsSkuPrice($tenant_id,$value['goods_spu'],$value['sku_id']);

            $total += $goods_price * $value['num'];
        }

        return $total;
    }

    //根据订单ID退回额度，增加退款记录
    public function creditBackByOrderPk($order_pk){
        //防止重复扣费
        $creditWhere = [
            'order_pk'=>$order_pk,
        ];
        $creditModel = new CreditDeductionModel;
        $creditResult = $creditModel->where($creditWhere)->find();

        if(!$creditResult)  return ['status'=>0, 'msg'=>'授信扣款订单不存在'];

        if($creditResult && 1 == $creditResult['is_refunded']){
            return ['status'=>1, 'msg'=>'已经退款了','data'=>$creditResult];
        }

        $userInfo = (new Users())->where('id',$creditResult['tenant_id'])->lock(true)->find();
        $userInfo->credit_available_amount += $creditResult['amount'];
        $ok1 =  $userInfo->save();

        $creditResult->is_refunded = 1;
        $ok2 = $creditResult->save();

        //throw new Exception(json_encode($creditResult));

        $creditAddData = [
            'order_pk'=>$order_pk,
            'order_no'=>$creditResult['order_no'],
            'amount'=>$creditResult['amount'],
            'account_residue'=>$userInfo->credit_available_amount,
            'tenant_id'=>$creditResult['tenant_id'],
            'is_increase'=>1,
            'transaction_type'=>1
        ];
        $ok3 = (new CreditDeductionModel())->save($creditAddData);

        if(!$ok1 || !$ok2 || !$ok3){
            return ['status'=>0, 'msg'=>'退款错误'];
        }
        return ['status'=>1, 'msg'=>'success'];
    }

    //候鸟订单数据入库
    public function hnCreateOrderSave($orderlist_pk,$data){
        $orderSonResult = (new OrderSon)->findBy($orderlist_pk);
        $orderResult = (new Order)->where('orderId',$orderSonResult['orderId'])->find();
        $order_pk = $orderResult['id'];

        $tenant_id =$orderResult->tenant_id;

        $apiOrderSonModel = new HnOrderDetail;

        $orderDetailArr = [];
        foreach ($data as $value) {
            $ord = $value;
            $ord['order_id'] = $order_pk;
            $ord['order_no'] = $value['order_no'];
            $ord['main_order_id'] = $orderSonResult['orderId'];
            $ord['source_order_no'] = $value['source_order_no'];
            $ord['tenant_id'] = $tenant_id;
            $ord['mall_order_status'] = $ord['order_status'];
            //$ord['creator_id'] = $creator_id;

            $ord['goods_spu'] = $value['order_goods']['goods_spu'];
            $ord['goods_sku'] = $value['order_goods']['sku_id'];
            $ord['sku_id'] = $value['order_goods']['sku_id'];
            $ord['goods_price'] = $value['order_goods']['goods_price'];
            $ord['goods_num'] = $value['order_goods']['goods_num'];
            $ord['goods_name'] = (new externalGoodsModel)->where('goods_spu', $ord['goods_spu'])->value('goods_name');

            if($tenant_id !== 0){
                $user = (new \catchAdmin\permissions\model\Users())->find($tenant_id);
            }

            $percent = (float) $user['qekj_tenant_goods_precent'];
            $ord['tenant_goods_price'] = round($ord['goods_price'] * $percent);


            //渠道商商品总额
            $ord['tenant_goods_money'] = $ord['tenant_goods_price'] * $ord['goods_num'];
            //渠道商 结算价格    ===  商品总额 + 运费 + 税差 - 优惠
            $ord['tenant_total_money'] = $ord['tenant_goods_money'] + $value['deliver_money'] + $value['tax_difference_money'] - $value['discount_money'];


            $orderDetailArr[] = $ord;
        }

        $orderResult->push_status = '待发货';
//        $orderResult->order_items = $data;//返回的api数据
        $res1 =  $orderResult->save();
        //推送后，创建明细单
        $res2 = $apiOrderSonModel->saveAll($orderDetailArr);

        $orderSonResult->api_return = $data;
        $orderSonResult->api_error = NULL;
        $orderSonResult->api_post_status = 1;

        $res3 = $orderSonResult->save();

        if(!$res1 || !$res2 || !$res3){
            return ['status'=>0, 'msg'=>'订单数据保存失败'];
        }

        return ['status'=>1, 'msg'=>'success'];
    }

    //海淘汇订单数据入库
    public function hthCreateOrderSave($orderlist_pk,$data){
        $orderSonResult = (new OrderSon)->findBy($orderlist_pk);
        $orderResult = (new Order)->where('orderId',$orderSonResult['orderId'])->find();
        $order_pk = $orderResult['id'];

        $tenant_id =$orderResult->tenant_id;

        $apiOrderSonModel = new HnOrderDetail;

        $orderDetailArr = [];
        foreach ($data['orderGoods'] as &$value) {
            $ord = $value;
            $ord['order_id'] = $order_pk;
            $ord['order_no'] = $data['order_sn'];
            $ord['main_order_id'] = $orderSonResult['orderId'];
            $ord['source_order_no'] = $orderSonResult['orderlistId'];
            $ord['tenant_id'] = $tenant_id;
            //$ord['creator_id'] = $creator_id;

            $ord['goods_spu'] = $value['sys_spu'];
            $ord['goods_sku'] = $value['sys_sku'];
            $ord['sku_id'] = $value['sys_sku'];

            //打一个布丁，因为接口没有商品单价，所以这里重新计算一下
            if((int) $value['product_num'] > 1 ){//购买多件
                $value['product_price'] = bcdiv($value['product_price'],$value['product_num'],2);
            }

            $ord['goods_price'] = $value['product_price'];//商品成本单价
            $ord['goods_money'] = $value['product_price'] * $ord['product_num'];//商品成本总价
            $ord['total_money'] = $value['product_price'] * $ord['product_num'];//订单商品 总金额（商品总价+其他例如运费）
            $ord['real_total_money'] = $value['product_price'] * $ord['product_num'];//实际支付金额 如果有优惠
            $ord['goods_num'] = $value['product_num'];//商品数量
            $ord['goods_name'] = (new externalGoodsModel)->where('goods_spu', $ord['goods_spu'])->value('goods_name');

            if($tenant_id !== 0){
                $user = (new \catchAdmin\permissions\model\Users())->find($tenant_id);
            }

            $percent = (float) $user['qekj_tenant_goods_precent'];
            $ord['tenant_goods_price'] = round($ord['goods_price'] * $percent);//渠道商商品价格


            //渠道商商品总额
            $ord['tenant_goods_money'] = $ord['tenant_goods_price'] * $ord['product_num'];//渠道商商品总价
            //渠道商 结算价格    ===  商品总额 + 运费 + 税差 - 优惠
            //$ord['tenant_total_money'] = $ord['tenant_goods_money'] + $value['deliver_money'] + $value['tax_difference_money'] - $value['deliver_money'];
            $ord['tenant_total_money'] = $ord['tenant_goods_price'] * $ord['product_num'];//渠道商订单总金额

            $orderDetailArr[] = $ord;
        }

        $orderResult->push_status = '待发货';
//        $orderResult->order_items = $data;//返回的api数据
        $res1 =  $orderResult->save();
        //推送后，创建明细单
        $res2 = $apiOrderSonModel->saveAll($orderDetailArr);

        $orderSonResult->api_return = $data;
        $orderSonResult->api_error = NULL;
        $orderSonResult->api_post_status = 1;
        $res3 = $orderSonResult->save();

        if(!$res1 || !$res2 || !$res3){
            return ['status'=>0, 'msg'=>'订单数据保存失败'];
        }

        return ['status'=>1, 'msg'=>'success'];
    }

    //候鸟子订单数据
    public function hnFormatApiOrderSonData($orderlist_pk, $data){

        //dd($data);

        $orderSonResult =  (new OrderSon())->findBy($orderlist_pk)->toArray();
        $orderResult =  (new Order)->where('orderId',$orderSonResult['orderId'])->find()->toArray();

        $xsResult = (new XsOrder())->where('merOrderId',$orderSonResult['orderId'])
            ->where('status',1)
            ->find();

        //$xsResult = $xsResult->toArray();

        $data['source_order_no'] = $orderSonResult['orderlistId'];
//        $data['source_platform_no'] = $orderSonResult['orderlistId'];
        $data['source_platform_no'] = $orderSonResult['orderId']; // 申报来源单号，还是用主单号

        $new_order_goods = [];
        $new_order_goods[] = [
            "goods_spu"=>$orderSonResult['productId'],
            "sku_id"=>$orderSonResult['sku_id'],
            "goods_num"=>$orderSonResult['num'],
            "goods_price"=>$orderSonResult['price'],
        ];

        $data['order_goods'] = $new_order_goods;

        return $data;
    }

    //海淘汇api订单数据
    public function hthFormatApiOrderData($order_pk, $data){
        //print_r($order_pk);

        //$order_pk = 116166;

        $orderResult =  (new Order)->findBy($order_pk)->toArray();
        $xsResult = (new XsOrder())->where('merOrderId',$orderResult['orderId'])
            ->where('status',1)
            ->find();


        //dd($xsResult);

        //省市区
        $full_area_arr = (new Areas)->where('area_id',$orderResult['area_id'])->find()->full_name;


        //推订单
        $orderData = [
//            "order_sn"=>Str::random(32),
            "order_sn"=>$orderResult['orderId'],
            "pay_type"=> "0",//支付方式
            "total_price"=>(string) $orderResult['amount'],
            "pay_price"=>(string) $orderResult['realPayment'],
                 "real_name"=>$data['username'],
            "user_phone"=>$orderResult['contactMobile'],
            "user_province"=>$full_area_arr[0],
            "user_city"=>$full_area_arr[1],
            "user_district"=>$full_area_arr[2],
            "user_address"=>$orderResult['detailAddr'],
                 "user_id_card"=>$data['id_card'],
            "pay_postage"=>(string) $orderResult['distributionfee'],
            "status"=>"0",//订单状态
            "origin_request"=>'12' ,
            "origin_response"=>'12' ,
            "platform_code"=>$orderResult['ebpCode'],
            "platform_name"=>$orderResult['ebpName'],
        ];

        if(!$xsResult){
            //return ['status'=>0, 'msg'=>'没有支付信息'];
            $orderData['pay_time'] = $orderResult['orderPayTime'];
            $orderData["pay_no"] = $orderResult['payOrderNo'];
        }else{
            $orderData['pay_time'] = date("Y-m-d H:i:s",strtotime($xsResult['completeTime']));
            $orderData["pay_no"] = $xsResult['checkOrgOrderNo'];
        }
        if(empty($orderData['pay_no'])){
            $orderData['pay_no'] = '123';
        }

        //$xsResult = $xsResult->toArray();

        if(!empty($data['declarer']) &&  !empty($data['declarer_id_card'])){//存在订购人
            if(empty($data['username']) || empty($data['id_card'])){//3种跨境都需要 收件人+身份，如果没有填写的问题
                $orderData['user_id_card'] = $data['declarer_id_card'];
                $orderData['real_name'] = $data['declarer'];
            }
        }

        $orderGoods = $orderResult['order_goods'];
        $new_order_goods = [];
        foreach ($orderGoods as $goods){
            $new_order_goods[] = [
                "product_num"=>$goods['goods_num'],
                "product_price"=>number_format($goods['goods_price'],2),
//                "sys_spu"=>"GH85518188DO",
                "sys_spu"=>$goods['goods_spu'],
//                "sys_sku"=>'9WIA56J3OP',
                "sys_sku"=>$goods['sku_id'],
                "tax_fee"=>"0.00",
                "postage_price"=>"0.00"
            ];
        }

        $orderData['order_goods'] = $new_order_goods;

        return $orderData;
    }

    //海淘汇api根据子订单数据
    public function hthFormatApiOrderSonData($orderlist_pk, $data){
        $orderSonResult =  (new OrderSon())->findBy($orderlist_pk)->toArray();
        $orderResult =  (new Order)->where('orderId',$orderSonResult['orderId'])->find()->toArray();

        $xsResult = (new XsOrder())->where('merOrderId',$orderSonResult['orderId'])
            ->where('status',1)
            ->find();

        //dd($xsResult);

        //省市区
        $full_area_arr = (new Areas)->where('area_id',$orderResult['area_id'])->find()->full_name;

        //推订单
        $orderData = [
//            "order_sn"=>$orderResult['orderId'],
            "order_sn"=>$orderSonResult['orderlistId'],
            "pay_type"=> "0",//支付方式
                "total_price"=>(string) $orderSonResult['amout'],//子订单金额
                "pay_price"=>(string) $orderSonResult['amout'],//子订单金额
            "real_name"=>$data['username'],
            "user_phone"=>$orderResult['contactMobile'],
            "user_province"=>$full_area_arr[0],
            "user_city"=>$full_area_arr[1],
            "user_district"=>$full_area_arr[2],
            "user_address"=>$orderResult['detailAddr'],
            "user_id_card"=>$data['id_card'],
            "pay_postage"=>(string) $orderResult['distributionfee'],
            "status"=>"0",//订单状态
            "origin_request"=>'12' ,
            "origin_response"=>'12' ,
            "platform_code"=>$orderResult['ebpCode'],
            "platform_name"=>$orderResult['ebpName'],
        ];

        $orderData['pay_time'] = date("Y-m-d H:i:s",strtotime($xsResult['completeTime']));
        $orderData["pay_no"] = $xsResult['checkOrgOrderNo'];

        if(in_array($orderSonResult['trade_type_name'],['保税直供'])){
            if(!$xsResult){
                //return ['status'=>0, 'msg'=>'没有支付信息'];
                $orderData['pay_time'] = $orderResult['orderPayTime'];
                $orderData["pay_no"] = $orderResult['payOrderNo'];
            }
        }

        if(empty($orderData['pay_no'])){
            $orderData['pay_no'] = '123';
        }

        //$xsResult = $xsResult->toArray();

        if(!empty($data['declarer']) &&  !empty($data['declarer_id_card'])){//存在订购人
            if(empty($data['username']) || empty($data['id_card'])){//3种跨境都需要 收件人+身份，如果没有填写的问题
                $orderData['user_id_card'] = $data['declarer_id_card'];
                $orderData['real_name'] = $data['declarer'];
            }
        }

        $new_order_goods = [];
        $new_order_goods[] = [
                "product_num"=>$orderSonResult['num'],
                "product_price"=>number_format($orderSonResult['price'],2),
                "sys_spu"=>$orderSonResult['productId'],
                "sys_sku"=>$orderSonResult['sku_id'],
                "tax_fee"=>"0.00",
                "postage_price"=>"0.00"
            ];

        $orderData['order_goods'] = $new_order_goods;

        return $orderData;
    }

    //行云api根据子订单数据
    public function xyFormatApiOrderSonData($orderlist_pk, $data){
        $orderSonResult =  (new OrderSon())->findBy($orderlist_pk)->toArray();
        $orderResult =  (new Order)->where('orderId',$orderSonResult['orderId'])->find()->toArray();

        $xsResult = (new XsOrder())->where('merOrderId',$orderSonResult['orderId'])
            ->where('status',1)
            ->find();

        //dd($xsResult);

        //省市区
        $full_area_arr = (new Areas)->where('area_id',$orderResult['area_id'])->find()->full_name;

        //创建订单
        $orderParams = [];
        if('保税直供' == $orderSonResult['trade_type_name']){
            $orderParams['order_type'] = 1;
        }else{
            $orderParams['order_type'] = 2;
        }

        $orderParams['merchant_order_id'] = $orderSonResult['orderlistId'];
        $orderParams['pay_type'] = 1;//余额支付

        if(1 == $orderParams['order_type']){//保税订单
            $orderParams['push_type'] = 1;
            $orderParams['buyer_name'] = $data['declarer'];//余额支付
            $orderParams['buyer_card_id'] = $data['declarer_id_card'];//身份证

            $orderParams['recipient_card_id'] = $data['id_card'];//收货人身份证

            $orderParams['custom_pay_order'] = $orderSonResult['orderId'];//清关单号（推支付单时带的订单号）【保税订单则为必填项】
            $orderParams['order_time'] = date("Y-m-d H:i:s",strtotime($xsResult['created_at']));//下单时间
            $orderParams['pay_time'] = date("Y-m-d H:i:s",strtotime($xsResult['completeTime']));//支付时间

            $orderParams['third_pay_type'] =15;
            $orderParams['pay_custom_no'] = $orderResult['paycomCode'];
            $orderParams['pay_company_name'] = $orderResult['paycomName'];
            $orderParams['pay_third_no'] = $xsResult['checkOrgOrderNo']; //交易流水号
            $orderParams['ecommerce_name'] = $orderResult['ebpName'];
            $orderParams['ecommerce_code'] = $orderResult['ebpCode'];
        }
        $orderParams['recipient_name'] = $data['username'];//收货人
        $orderParams['recipient_mobile'] = $orderResult['contactMobile'];//收货人手机号
        $orderParams['order_province'] = $full_area_arr[0];//省
        $orderParams['order_city'] = $full_area_arr[1];//省
        $orderParams['order_area'] = $full_area_arr[2];//省
        $orderParams['order_address'] = $orderResult['detailAddr'];//详细地址

        $sku_list =[
            [
                'sku_id'=>$orderSonResult['sku_id'],
                'package_num'=>1,//包装规格
                'buy_num'=>$orderSonResult['num'],
//                'sku_price'=>'0.01',
                'sku_price'=>number_format($orderSonResult['price'],2),
                'sku_discount_amount'=>'0.00',//平台优惠金额
                'channel_discount_amount'=>'0.00',//渠道优惠金额
//                'sku_pay_amount'=>number_format($orderSonResult['price'],2),
                'sku_pay_amount'=>number_format($orderSonResult['amout'],2),
                'price_type'=> $orderParams['order_type'] == 1 ? 2 : 1,
            ]
        ];

        // 对每个商品的字段按字母顺序排序
        foreach ($sku_list as &$sku) {
            ksort($sku); // 按键名升序排序
        }
        unset($sku); // 解引用以避免修改原数组

        $orderParams['sku_list'] = $sku_list;
        $orderParams['order_pay_amount'] = (string) $orderSonResult['amout'];//终端支付总金额
        $orderParams['order_discount_amount'] = '0.00';//平台优惠总金额
        $orderParams['channel_discount_amount'] = '0.00';//渠道优惠总金额
        $orderParams['order_freight_amount'] = '0.00';//运费总金额
        $orderParams['order_total_amount'] = (string) $orderSonResult['amout'];//订单总金额

        if($orderParams['order_type'] == 1){//保税订单，单独处理部分数据
            $orderParams['sku_list'][0]['sku_discount_amount'] = $orderResult['discount']; //sku平台优惠金额
            $orderParams['sku_list'][0]['sku_pay_amount'] = $orderResult['realPayment']; //sku终端支付金额

            $orderParams['order_discount_amount'] = $orderResult['discount'];//平台优惠总金额
            $orderParams['order_pay_amount'] = (string) $orderResult['realPayment'];//终端支付总金额
            $orderParams['order_total_amount'] = (string) $orderResult['amount'];//订单总金额

            if(!$xsResult){
                //return ['status'=>0, 'msg'=>'没有支付信息'];
                $orderParams['custom_pay_order'] =$orderSonResult['orderId'];
                $orderParams['order_time'] = $orderResult['orderPayTime'];
                $orderParams['pay_time'] = $orderResult['orderPayTime'];

                $orderParams['pay_third_no'] = '123'; //交易流水号
            }
        }

        //$xsResult = $xsResult->toArray();

        if(!empty($data['declarer']) &&  !empty($data['declarer_id_card'])){//存在订购人
            if(empty($data['username']) || empty($data['id_card'])){//3种跨境都需要 收件人+身份，如果没有填写的问题
                $orderParams['recipient_card_id'] = $data['declarer_id_card'];
                $orderParams['recipient_name'] = $data['declarer'];
            }
        }
        //print_r($orderParams);

        return $orderParams;
    }
}